package org.shj.spark.streaming;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaPairReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.kafka.KafkaUtils;

import scala.Tuple2;

/**
 * 可以在本地运行，需要先启动zookeeper和kafka
 * @author Administrator
 *
 */
public class KafkaWordCount {

	public static void main(String[] args) throws Exception{
		SparkConf conf = new SparkConf().setAppName("KafkaWordCount");
		conf.setMaster("local[*]");
		JavaStreamingContext jsc = new JavaStreamingContext(conf, Durations.seconds(10));
		jsc.sparkContext().setLogLevel("WARN");
		
		Map<String, Integer> topics = new HashMap<String, Integer>();
		topics.put("shjtest", 1);
		
		JavaPairReceiverInputDStream<String, String> lines = KafkaUtils.createStream(jsc, 
				"ubuntu3:2181,ubuntu4:2181,ubuntu5:2181", 
				"MyFirstConsumerGroup", 
				topics);
		
		JavaDStream<String> words = lines.flatMap(new FlatMapFunction<Tuple2<String,String>, String>() {
			private static final long serialVersionUID = -5624870488125722641L;

			@Override
			public Iterator<String> call(Tuple2<String, String> line) throws Exception {
				return Arrays.asList(line._2.split("\\s+")).iterator();
			}
		});
		
		JavaPairDStream<String, Integer> result = words.mapToPair(new PairFunction<String, String, Integer>() {
			private static final long serialVersionUID = -3727931005625846885L;

			@Override
			public Tuple2<String, Integer> call(String word) throws Exception {
				return new Tuple2<String, Integer>(word,1);
			}
		}).reduceByKey(new Function2<Integer, Integer, Integer>() {
			private static final long serialVersionUID = -3169632339714592212L;

			public Integer call(Integer v1, Integer v2) throws Exception {
				return v1 + v2;
			}
		});
		
		result.print();
		
		jsc.start();
		jsc.awaitTermination();
		
		jsc.stop();

	}

}
